package com.ygxsk.carhome.ui.care;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gyf.immersionbar.ImmersionBar;
import com.kongzue.dialogx.dialogs.PopTip;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.alertview.AlertView;
import com.ygxsk.carhome.constant.ConstantApi;
import com.ygxsk.carhome.constant.ConstantSign;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.constant.ExtraValue;
import com.ygxsk.carhome.enumwrap.CardAuditStatus;
import com.ygxsk.carhome.listener.DoSomeThingListener;
import com.ygxsk.carhome.listener.DoubleClickListener;
import com.ygxsk.carhome.listener.ErrorParentExtraSingle;
import com.ygxsk.carhome.response.CouponCustomerVo;
import com.ygxsk.carhome.response.CouponCustomerVoOutSide;
import com.ygxsk.carhome.retrofit.AddLogUpLoadInfo;
import com.ygxsk.carhome.retrofit.ApiException;
import com.ygxsk.carhome.retrofit.ApiRequestSubListener;
import com.ygxsk.carhome.retrofit.ApiService;
import com.ygxsk.carhome.retrofit.ErrorConsumer;
import com.ygxsk.carhome.retrofit.NetworkManager;
import com.ygxsk.carhome.retrofit.ResponseTransformer;
import com.ygxsk.carhome.ui.ErrorActivity;
import com.ygxsk.carhome.ui.adapter.CardSumHistoryAdapter;
import com.ygxsk.carhome.utils.CommTools;
import com.ygxsk.carhome.utils.CommUtils;
import com.ygxsk.carhome.views.MyLinearLayoutManager;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/*
 * @Author:itchenqi175@163.com
 * @Time:2023-07-25  21:36
 * @Description:发放记录-更多按钮过来的，卡券发放的历史页面，发放了多少，有个记录等；发放了哪些人，是这个员工发放的哪些人；
 */
public class CardSumHistoryActivity extends ErrorActivity implements ErrorParentExtraSingle {

    public interface ChooseListenerInCard {

        //2018年08月09日去掉全选功能的
        void chooseAllItem();

        void unChooseAllItem();

    }

    @BindView(R.id.refreshlayoutinsumhistorycommon)
    SmartRefreshLayout refreshLayoutInSumHistory;

    @BindView(R.id.recyclerviewinsumhistorycommon)
    RecyclerView recyclerViewInSumHistory;

    //顶部的包裹布局
    @BindView(R.id.layoutbuttoncheckwarp)
    RelativeLayout layoutButtonCheckWarp;


    @BindView(R.id.relacontentallselect)
    RelativeLayout relaContentAllSelect;

    //选中
    @BindView(R.id.checkBoxSelectAll)
    CheckBox checkBoxSelectAll;

    //选中了几条
    @BindView(R.id.textviewdatasize)
    TextView textViewDataSize;

    //该优惠券的详细信息
    private MaterialDialog materialDialogCustomView;


    /**
     * 标记选中和未选中两种状态
     */
    private boolean isSelectAll;


    //潜在客户，
    private ArrayList<CouponCustomerVo> mDataResources = new ArrayList<CouponCustomerVo>();

    //列表的历史记录：
    private CardSumHistoryAdapter cardSumHistoryAdapter;

    //最后一条上传的id的信息内容
    private int pagination_upLoad = Parameterkey.pageNum_default_first;

    //上传携带过来的-优惠券大礼包的id内容。
    private String couponPackId_upLoad;

    //默认是不是多个筛选过来的，默认是单个审核优惠券。
    protected boolean extra_ischecked_more_items_flag = false;

    //为了做释放
//    private CustomAttachPopupBg customAttachBg;


    private ChooseListenerInCard chooseListenerFunction = new ChooseListenerInCard() {

        @Override
        public void chooseAllItem() {

            if (cardSumHistoryAdapter != null) {

                if (!isSelectAll) {//如果未被选中

                    //2018年08月09日修改的说是全选功能暂时去掉如下四行代码
                    isSelectAll = true;

                    if (checkBoxSelectAll != null) {
                        checkBoxSelectAll.setChecked(true);
                    }

                    //如果都未被选中，那么选中
                    cardSumHistoryAdapter.selectedAll();

                    //重新计算价格
                    method_total_size(mDataResources);

                } else if (isSelectAll) {//如果此刻是被选中的
                    //2018年08月09日修改的说是全选功能暂时去掉如下四行代码
                    //===============================================================================
                    isSelectAll = false;

                    if (checkBoxSelectAll != null) {
                        checkBoxSelectAll.setChecked(false);
                    }

                    cardSumHistoryAdapter.unSelectedAll();

                    //重新计算价格
                    method_total_size(mDataResources);
                    //===============================================================================
                }

            }

        }

        //2018年08月09日添加全选不可用且中间不让点击内容
        @Override
        public void unChooseAllItem() {
            //2018年08月09日添加全选不可用且中间不让点击内容
            //如果不被全选中
            //================================================================================
            isSelectAll = false;

            if (checkBoxSelectAll != null) {
                checkBoxSelectAll.setChecked(false);
            }

            method_total_size(mDataResources);
            //================================================================================
        }
    };


    @OnClick({R.id.buttonnextroundsubmit, R.id.relacontentallselect})//提交审核和全选按钮
    public void clickInCardSumHistory(View view) {

        switch (view.getId()) {

            case R.id.buttonnextroundsubmit: {

                //提交审核
                if (!DoubleClickListener.isFastDoubleClick()) {

                    if (NetworkUtils.isConnected()) {

                        //做循环判断,选出待审核项
                        ArrayList<String> arrayList_upLoad = new ArrayList<>();

                        for (int index = 0; index < mDataResources.size(); index++) {

                            int isCheckedin = mDataResources.get(index).getIsSelect();

                            if (isCheckedin == 1) {

                                int couponCustomerId = mDataResources.get(index).getCouponCustomerId();

                                arrayList_upLoad.add(String.valueOf(couponCustomerId));//添加id类

                            } else {
                                //retain
                            }

                        }

                        //如果列表是空，说明没有选中待审核项
                        if (arrayList_upLoad != null && arrayList_upLoad.isEmpty()) {
                            CommUtils.checkDialog(mAlertView);
                            mAlertView = CommUtils.method_showAlertViewSingleSlowly(mActivityInstance, ConstantSign.ALERT_TITLE, getString(R.string.choose_coupon_item), true);
                            mAlertView.show();
                            return;
                        }

//                        mAlertView = new AlertView(getResources().getString(R.string.clearaddorsubmitsuretitletips),//
//                                getString(R.string.choose_coupon_item), //请选择待审核的优惠券
//                                null,//
//                                new String[]{ConstantSign.ALERT_SINGLE}, //
//                                null, //
//                                CardSumHistoryActivity.this, //
//                                AlertView.Style.Alert,//
//                                new com.ygxsk.carhome.alertview.OnItemClickListener() {//
//                                    @Override
//                                    public void onItemClick(Object o, int position) {
//                                        //
//                                    }
//                                });
//
//                        mAlertView.setCancelable(true)//
//                                .show();//

                        //直接的审核上传接口
                        CommUtils.checkDialog(mAlertView);
                        mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                StringUtils.getString(R.string.clearaddorsubmitsuremessage),//提示内容
                                StringUtils.getString(R.string.clearcachecancel), //取消
                                new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                null, mActivityInstance, AlertView.Style.Alert, new com.ygxsk.carhome.alertview.OnItemClickListener() {//
                            @Override
                            public void onItemClick(Object o, int position) {

                                if (position != AlertView.CANCELPOSITION) {

                                    method_gainVerifySubmitInfo_upLoad_moreItems(arrayList_upLoad);

                                }
                            }
                        });

                        mAlertView.setCancelable(true);
                        mAlertView.show();


                    } else {
//                        CommUtils.displayToastShort(PropertyPaymentActivity.this, ConstantApi.NETWORKFAIL);
                        ToastUtils.showShort(getResources().getString(R.string.http_exception_network));
                    }

                }

                break;

            }

            case R.id.relacontentallselect: {

                //全选或者不全选
                method_selectAll();

                break;
            }

            default:
                break;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivityInstance = this;

        if (mDataResources == null) {
            mDataResources = new ArrayList<>();
        }

//        if (dataListFromWhere == null) {
//            dataListFromWhere = new ArrayList<>();
//        }
//        if (dataListStateItem == null) {
//            dataListStateItem = new ArrayList<>();
//        }

        processExtraData();

        initloading();

        initViews();

        gainDatas();

        //这里有页面刷新，或者编辑完毕，通知页面刷新的逻辑；
//        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);
//        }

    }

    @Override
    protected int getContentViewId() {
        //原始代码是这个
        //return R.layout.activity_card_verifi;
        return R.layout.activiry_card_sum_history;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();

        ImmersionBar.with(this)//
                .titleBar(R.id.toolbarygxskout)
                .fitsSystemWindows(true)//解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                //.statusBarColor(R.color.colorPrimary)//
                //.navigationBarColor(R.color.colorPrimary)//
                //.keyboardEnable(true)
                .init();
    }

    @Override
    protected void initToolBar(ToolbarHelper toolbarHelper) {

        //卡券发放记录：
        toolbarHelper.setTitle(getString(R.string.title_smart_go_history));
        toolbarHelper.setVersionName(true, AppUtils.getAppVersionName());
        toolbarHelper.setLayoutClose(false, "", null);

        toolbarHelper.setLayoutLeft(true, R.drawable.backicon, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索客户信息，优先关闭软键盘
                KeyboardUtils.hideSoftInput(mActivityInstance);
                methodBack();
            }
        });

        //这里是什么都没有的；
        toolbarHelper.setLayoutRight(false, 1, "", null);
//        toolbarHelper.setLayoutRight(false, 1, "", new ClickUtils.OnDebouncingClickListener() {
//            @Override
//            public void onDebouncingClick(View v) {
//            }
//        });

        //2024-1-10 14:00:58新增的特殊图片
//        toolbarHelper.setImageViewRight(true, R.drawable.icon_rigad, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
////                new XPopup.Builder(mActivityInstance)
////                        .hasShadowBg(false)
////                        .isTouchThrough(true)
////                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//////                        .atView(toolbarHelper.getImageViewRight())
//////                        .atView(toolbarHelper.getToolbar().findViewById(R.id.imageviewinphone))
////                        .atView(imageViewRight)
////                        .isCenterHorizontal(true)
////                        .hasShadowBg(false) // 去掉半透明背景
////                        .asCustom(new RightBubbleAttachPopup(mActivityInstance))
////                        .show();
//
////                showPop();
////                toggleBright();
//
//                customAttachBg = (CustomAttachPopupBg) new XPopup.Builder(mActivityInstance)
//                        .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
//                        .isCoverSoftInput(false)//
//                        .atView(v)
//                        .hasShadowBg(true)//是否展示背景
//                        .asCustom(new CustomAttachPopupBg(mActivityInstance))
//                        .show();
//
//            }
//        });

    }

    @Override
    protected void onClickNodata(View v) {

        gainDatas();

    }

    @Override
    protected void initViews() {

        //----------------------------------------------------------------------------------------------------
        //如果是 批量审核过来的，那么底部布局要展示
        if (extra_ischecked_more_items_flag) {

            if (layoutButtonCheckWarp != null) {
                layoutButtonCheckWarp.setVisibility(View.VISIBLE);
            }

            //首先填充一下数量,在底部显示的时候。
            method_total_size(mDataResources);

        } else {
            if (layoutButtonCheckWarp != null) {
                layoutButtonCheckWarp.setVisibility(View.GONE);
            }
        }
        //----------------------------------------------------------------------------------------------------
        //布局的适配器填充，下拉刷新等等；
        recyclerViewInSumHistory.setLayoutManager(new MyLinearLayoutManager(this));
        cardSumHistoryAdapter = new CardSumHistoryAdapter(R.layout.cardsumhistoryadapter, mDataResources, extra_ischecked_more_items_flag);
        recyclerViewInSumHistory.setAdapter(cardSumHistoryAdapter);
        cardSumHistoryAdapter.notifyDataSetChanged();

        //如果是 批量审核过来的，可以点击操作，如果不是批量审核过来的，那么就不能点击任何操作。
        if (extra_ischecked_more_items_flag) {


            cardSumHistoryAdapter.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                    // TODO: 2023-07-13 15:07 跳转到这个客户的详情页面.
//                Bundle extra_bundle = new Bundle();
//                extra_bundle.putParcelable(ExtraKey.EXTRA_RUNMANGROUPMANAGEBEAN, runManGroupManageBeanItem);
//                ActivityUtils.startActivity(extra_bundle, LeadDetailActivity.class);

                    CouponCustomerVo couponCustomerVo = (CouponCustomerVo) adapter.getItem(position);

                    if (couponCustomerVo != null) {

                        int isChecked = couponCustomerVo.getIsSelect();
                        //ToastUtils.showShort("点击了图片内容");
                        if (isChecked == 0) {
                            couponCustomerVo.setIsSelect(1);

                        } else if (isChecked == 1) {
                            couponCustomerVo.setIsSelect(0);
                        }

                        //采集当前列表的选中状态
                        ArrayList<Boolean> tempBooleans = new ArrayList<>();

                        for (int index = 0; index < mDataResources.size(); index++) {

                            int currentState = mDataResources.get(index).getIsSelect();
                            if (currentState == 0) {
                                tempBooleans.add(false);
                            } else if (currentState == 1) {
                                tempBooleans.add(true);
                            }

                        }

                        for (int pos = 0; pos < mDataResources.size(); pos++) {

                            int curState = mDataResources.get(pos).getIsSelect();

                            if (curState == 0) {//如果发现有一个未选中,取消全选状态，终止循环。
                                chooseListenerFunction.unChooseAllItem();
                                break;

                            } else if (curState == 1) {
                                //如果发现有一个是选中状态，可以不管，如果发现所有列表全是选中状态，则全选勾中
                                if (tempBooleans.contains(false)) {
                                    //如果有包含未选中的(换言之就是:列表里有未被选中的,那么可以忽略)
                                } else {
                                    chooseListenerFunction.chooseAllItem();
                                    break;
                                }
                            }
                        }

                        //这里需要重新刷新 因为列表有复用的情况
                        if (adapter != null) {
                            adapter.notifyDataSetChanged();
                        }

                        //计算总个数内容。
                        method_total_size(mDataResources);

                    }
                }
            });

        } else {

            LogUtils.d(ConstantSign.LOGCAT_NOMAL + "不是 批量审核 过来的");

        }

        cardSumHistoryAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                CouponCustomerVo couponCustomerVo = (CouponCustomerVo) adapter.getItem(position);

                switch (view.getId()) {


                    case R.id.imagerightinfoclickhis: {//查看优惠券的发送原因

                        if (couponCustomerVo != null) {

//                            String couponName = couponCustomerVo.getCouponName();
//                            String explain = couponCustomerVo.getExplain();
//                            CommUtils.alertMaterialDialog(mActivityInstance, couponCustomerVo.getCouponName(), couponCustomerVo.getExplain());

                            CommUtils.checkMaterialDialog(materialDialogCustomView);

                            materialDialogCustomView = CommTools.function_show_dialog_seeReason(flag_jumpfrom_where, //
                                    mActivityInstance,//
                                    mActivityInstance,//
                                    couponCustomerVo, //
                                    new DoSomeThingListener() {
                                        @Override
                                        public void doSomeThing() {

                                            if (materialDialogCustomView != null) {
                                                materialDialogCustomView.dismiss();
                                                materialDialogCustomView = null;
                                            }

                                        }
                                    });

                        }

                        break;
                    }

                    case R.id.textviewcarsendreasonhis: {//查看原因的文字

                        if (couponCustomerVo != null) {

//                            String explain = couponCustomerVo.getExplain();
//                            String couponName = couponCustomerVo.getCouponName();
//                            CommUtils.alertMaterialDialog(mActivityInstance, couponCustomerVo.getCouponName(), couponCustomerVo.getExplain());

                            CommUtils.checkMaterialDialog(materialDialogCustomView);

                            materialDialogCustomView = CommTools.function_show_dialog_seeReason(flag_jumpfrom_where, //
                                    mActivityInstance,//
                                    mActivityInstance,//
                                    couponCustomerVo, //
                                    new DoSomeThingListener() {
                                        @Override
                                        public void doSomeThing() {

                                            if (materialDialogCustomView != null) {
                                                materialDialogCustomView.dismiss();
                                                materialDialogCustomView = null;
                                            }

                                        }
                                    });

                        }

                        break;

                    }

//                    case R.id.textvieweditviewphonehis: {//这里的点击有一些消耗条目的点击，条目是点击勾选
//
//                        if (couponCustomerVo != null) {
//                            clickButton_toCallPhone(CardSumHistoryActivity.this, couponCustomerVo.getPhone(), CallHistoryBusinessType.BUSINESSTYPE_9.getIndex());
//                        }
//
//                        break;
//                    }

                    case R.id.roundtextViewDoVerifyTwo: {//添加审核逻辑

                        if (couponCustomerVo != null) {

                            CommUtils.checkDialog(mAlertView);
                            mAlertView = new AlertView(StringUtils.getString(R.string.clearaddorsubmitsuretitletips), //提示
                                    StringUtils.getString(R.string.submit_consign_verify_message_sure),//提示内容 确定审核通过
                                    StringUtils.getString(R.string.clearcachecancel), //取消
                                    new String[]{StringUtils.getString(R.string.clearaddorsubmitsure)},//确定
                                    null, mActivityInstance, AlertView.Style.Alert, new com.ygxsk.carhome.alertview.OnItemClickListener() {//
                                @Override
                                public void onItemClick(Object o, int position) {

                                    if (position != AlertView.CANCELPOSITION) {

                                        //"couponCustomerId": 62986, //发放的优惠券记录主键Id
                                        //"couponId": 1, //优惠券主键Id
                                        //"auditStatus": 1 //审核状态 0：待审核 1：审核通过 2：审核不通过

                                        method_gainVerifySubmitInfo_upLoad(couponCustomerVo.getCouponCustomerId(), couponCustomerVo.getCouponId(), couponCustomerVo.getAuditStatus());

                                    }

                                }
                            });

                            mAlertView.setCancelable(true);
                            mAlertView.show();

                        }

                        break;
                    }

                    default:
                        break;
                }


            }
        });

        refreshLayoutInSumHistory.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        gainDatas();

                        refreshLayout.finishRefresh();

                    }
                });

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {

                        if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                            getServerDatas_for_rice_tick_history();

                        } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                            getServerDatas();

                        } else {
                            //额外的
                            getServerDatas();
                        }

                        refreshLayout.finishLoadMore();

                    }
                });
            }
        });


    }

    @Override
    protected void gainDatas() {

        pagination_upLoad = Parameterkey.pageNum_default_first;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (NetworkUtils.isConnected()) {

            if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY) {

                getServerDatas_for_rice_tick_history();

            } else if (flag_jumpfrom_where == ExtraValue.VALUE_JUMP_FORM_CARD_MAIN_ACTIVITY) {

                //如果是从客户关怀过来的，它是区分【单个审核】和【批量审核】的。
                getServerDatas();

            } else {
                //额外的
                getServerDatas();
            }

        } else {
            netWorkError();
            setEnableLoadmore(refreshLayoutInSumHistory, false);
        }


    }

    private void getServerDatas_for_rice_tick_history() {

        //ExtraValue.VALUE_JUMP_FORM_RICE_TICKET_OUT_ACTIVITY
        //获取的优惠券的历史：历史记录--这个员工发放过的 优惠券 有张三-李四-王五的；
        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
        map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
        map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERCOUPONLISTPAGEFORMEMBERRICETICK_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponListPageForMemberRiceTick_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .getCustomerCouponListPageForMemberRiceTick(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardSumHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        //methodNotSuccessData(what_method, serverCode, serverMessage);
                        // : 2023-08-15 14:32 这里还有更好的处理办法，使用BRAV自己的遮盖

                        if (mDataResources != null && mDataResources.isEmpty()) {

                            CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                                    serverCode,//
                                    R.drawable.errorsear,//
                                    serverMessage,//
                                    getString(R.string.nulldatanow));

                        }

                        // : 2023-08-14 21:20 是否要弹窗提示`

                    }
                })).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Throwable {
                        loadingGone();
                        setEnableLoadmore(refreshLayoutInSumHistory, true);
                    }
                }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                    @Override
                    public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                        method_handler_success(couponCustomerVoOutSide);

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {
                        //页面报错；
                        function_apiException(apiException);
                    }

                });


    }

    private void getServerDatas() {


        //        CardAuditStatus {
//            //审核状态 0：待审核 1：审核通过 2：审核不通过
//                    STATUS_NOT_VERIFY("0", "待审核"),
//                    STATUS_HAS_VERIFY("1", "审核通过"),
//                    STATUS_CANNOT_VERIFY("2", "审核不通过");

        if (extra_ischecked_more_items_flag) {

            //如果是批量审核过来的。
            HashMap<String, Object> map = new HashMap<>();
            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id

            map.put(Parameterkey.couponPackId, couponPackId_upLoad);//
            map.put(Parameterkey.auditStatus, CardAuditStatus.STATUS_NOT_VERIFY.getIndex());//
            map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
            map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
            addLogUpLoadInfo.setActivity(mActivityInstance);
            addLogUpLoadInfo.setWhat(ConstantApi.WHAT_GETCUSTOMERCOUPONLISTPAGEBYPACK_URL);//请求数字标识
            addLogUpLoadInfo.setUrlPath(ApiService.getCustomerCouponListPageByPack_url);//url地址
            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
            addLogUpLoadInfo.setHashMapParameter(map);

            NetworkManager.getInstance().initRetrofitRxJava()
                    .create(ApiService.class)
                    .getCustomerCouponListPageByPack(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                            MediaType.parse(ApiService.HEADER_JSON)))
                    .compose(CardSumHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                        @Override
                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                            //methodNotSuccessData(what_method, serverCode, serverMessage);

                            if (mDataResources != null && mDataResources.isEmpty()) {

                                CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                                        serverCode,//
                                        R.drawable.errorsear,//
                                        serverMessage,//
                                        getString(R.string.nulldatanow));

                            }

                            // TODO: 2023-08-14 21:20 是否要弹窗提示


                        }
                    })).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Throwable {
                            loadingGone();
                            setEnableLoadmore(refreshLayoutInSumHistory, true);
                        }
                    }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                        @Override
                        public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                            method_handler_success(couponCustomerVoOutSide);

                            //如果是刷新礼包的类别，那么要清空【全选】选中状态。


                        }

                    }, new ErrorConsumer() {

                        @Override
                        protected void error(ApiException apiException) {
                            //页面报错；
                            if (apiException != null) {
                                if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                    ToastUtils.showShort(apiException.getDisplayMessage());
                                }
                            }
                        }
                    });


        } else {

            HashMap<String, Object> map = new HashMap<>();
            map.put(Parameterkey.shopInfoId, mSession.getShopInfoId());//,
//        map.put(Parameterkey.customerId, _customerId);//填充搜索出来的这个客户的 唯一id
            map.put(Parameterkey.pagination, pagination_upLoad);//传递的页码
            map.put(Parameterkey.pageSize, Parameterkey.pageSize_default);//,搜索关键字

            AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
            addLogUpLoadInfo.setActivity(mActivityInstance);
            addLogUpLoadInfo.setWhat(ConstantApi.GETSHOPLATENTCUSTOMERLIST_URL);//请求数字标识
            addLogUpLoadInfo.setUrlPath(ApiService.getShopLatentCustomerList_url);//url地址
            addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
            addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
            addLogUpLoadInfo.setHashMapParameter(map);

            NetworkManager.getInstance().initRetrofitRxJava()
                    .create(ApiService.class)
                    .getCustomerCouponListPageForMember(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                            MediaType.parse(ApiService.HEADER_JSON)))
                    .compose(CardSumHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
                    .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<CouponCustomerVoOutSide>() {
                        @Override
                        public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                            super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
                            //methodNotSuccessData(what_method, serverCode, serverMessage);
                            if (mDataResources != null && mDataResources.isEmpty()) {
                                CommUtils.checkCurrently((ErrorActivity) mActivityInstance,//
                                        serverCode,//
                                        R.drawable.errorsear,//
                                        serverMessage,//
                                        getString(R.string.nulldatanow));
                            }

                            // TODO: 2023-08-14 21:20 是否要弹窗提示


                        }
                    })).doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Throwable {
                            loadingGone();
                            setEnableLoadmore(refreshLayoutInSumHistory, true);
                        }
                    }).subscribe(new Consumer<CouponCustomerVoOutSide>() {
                        @Override
                        public void accept(CouponCustomerVoOutSide couponCustomerVoOutSide) throws Throwable {

                            method_handler_success(couponCustomerVoOutSide);

                        }
                    }, new ErrorConsumer() {

                        @Override
                        protected void error(ApiException apiException) {
                            //页面报错；
                            if (apiException != null) {
                                if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                    ToastUtils.showShort(apiException.getDisplayMessage());
                                }
                            }
                        }
                    });
        }

    }


    //优惠券的批量审核，多个一起审核。
    private void method_gainVerifySubmitInfo_upLoad_moreItems(ArrayList<String> _couponIdList) {

//        {
//                "couponCustomerId": 62986, //发放的优惠券记录主键Id
//                "couponId": 1, //优惠券主键Id
//                "auditStatus": 1 //审核状态 0：待审核 1：审核通过 2：审核不通过
//        }

//        CardAuditStatus {
//            //审核状态 0：待审核 1：审核通过 2：审核不通过
//                    STATUS_NOT_VERIFY("0", "待审核"),
//                    STATUS_HAS_VERIFY("1", "审核通过"),
//                    STATUS_CANNOT_VERIFY("2", "审核不通过");


        HashMap<String, Object> map = new HashMap<>();
//        map.put(Parameterkey.couponCustomerId, _couponCustomerId);//
        map.put(Parameterkey.ids, _couponIdList);
        map.put(Parameterkey.auditStatus, CardAuditStatus.STATUS_HAS_VERIFY.getIndex());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEAUDITSTATUSBYIDS_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateAuditStatusByIds_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateAuditStatusByIds(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardSumHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);

                        method_handler_success_server_for_upLoad();

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });
    }

    //处理 单个审核或者批量审核完毕之后的后续操作。
    private void method_handler_success_server_for_upLoad() {

        //bug 2023-12-7 11:17:52 需要同步刷新 客户关怀主页列表：
        //餐券也类似
//        EventCardMain eventCardMain = new EventCardMain();
//        eventCardMain.setMessage(ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CARD_MAIN_LIST);
//        EventBus.getDefault().post(eventCardMain);

        methodSubmitSuccess(CardSumHistoryActivity.this, new DoSomeThingListener() {
            @Override
            public void doSomeThing() {

                //通知主页列表刷新
                pagination_upLoad = Parameterkey.pageNum_default_first;

                if (mDataResources != null && !mDataResources.isEmpty()) {
                    mDataResources.clear();
                }

                if (cardSumHistoryAdapter != null) {
                    cardSumHistoryAdapter.notifyDataSetChanged();
                }

                getServerDatas();

            }
        });
    }


    //单个的优惠券的审核
    private void method_gainVerifySubmitInfo_upLoad(Integer _couponCustomerId, String _couponId, Integer _auditStatus) {

//        {
//                "couponCustomerId": 62986, //发放的优惠券记录主键Id
//                "couponId": 1, //优惠券主键Id
//                "auditStatus": 1 //审核状态 0：待审核 1：审核通过 2：审核不通过
//        }

//        CardAuditStatus {
//            //审核状态 0：待审核 1：审核通过 2：审核不通过
//                    STATUS_NOT_VERIFY("0", "待审核"),
//                    STATUS_HAS_VERIFY("1", "审核通过"),
//                    STATUS_CANNOT_VERIFY("2", "审核不通过");

        HashMap<String, Object> map = new HashMap<>();
        map.put(Parameterkey.couponCustomerId, _couponCustomerId);//
        map.put(Parameterkey.couponId, _couponId);
        map.put(Parameterkey.auditStatus, CardAuditStatus.STATUS_HAS_VERIFY.getIndex());

        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
        addLogUpLoadInfo.setActivity(mActivityInstance);
        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_UPDATEAUDITSTATUS_URL);//请求数字标识
        addLogUpLoadInfo.setUrlPath(ApiService.updateAuditStatus_url);//url地址
        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_POST);//POST 或者 GET
        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
        addLogUpLoadInfo.setHashMapParameter(map);

        NetworkManager.getInstance().initRetrofitRxJava()
                .create(ApiService.class)
                .updateAuditStatus(RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue),
                        MediaType.parse(ApiService.HEADER_JSON)))
                .compose(CardSumHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))
                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<String>() {
                    @Override
                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);

                        if (!TextUtils.isEmpty(serverMessage)) {
                            PopTip.show(serverMessage).iconWarning();
                        }

                    }
                })).subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String stringValue) throws Throwable {

                        //TipDialog.show(StringUtils.getString(R.string.add_submit_success), WaitDialog.TYPE.SUCCESS);
                        method_handler_success_server_for_upLoad();

                    }
                }, new ErrorConsumer() {

                    @Override
                    protected void error(ApiException apiException) {

                        if (apiException != null) {
                            if (!TextUtils.isEmpty(apiException.getDisplayMessage())) {
                                ToastUtils.showShort(apiException.getDisplayMessage());
                            }
                        }

                    }
                });
    }

    //多个接口通用的
    private void method_handler_success(CouponCustomerVoOutSide _couponCustomerVoOutSide) {

        if (_couponCustomerVoOutSide != null) {

            ArrayList<CouponCustomerVo> couponCustomerVos = _couponCustomerVoOutSide.getDataList();

            if (couponCustomerVos != null && !couponCustomerVos.isEmpty()) {
                if (mDataResources != null) {
                    mDataResources.addAll(couponCustomerVos);
                }
            }

        }

        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
        if (mDataResources != null && mDataResources.isEmpty()) {

            if (refreshLayoutInSumHistory != null) {
                refreshLayoutInSumHistory.setEnableLoadMore(false);
            }

            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);

        }

        if (cardSumHistoryAdapter != null) {
            cardSumHistoryAdapter.notifyDataSetChanged();
        }

        pagination_upLoad = _couponCustomerVoOutSide.getNextPagination();

        //对列表改造：
        if (pagination_upLoad == Parameterkey.GET_NEXT_PAGINATION) {
            setFinishLoadMoreWithNoMoreData(refreshLayoutInSumHistory, true);
        } else {
            setEnableLoadmore(refreshLayoutInSumHistory, true);
        }

        // TODO: 2024/1/11 15:41 特殊操作的一个部分是重新计算数字
        method_total_size(mDataResources);

    }


//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onEventMainThreadInCardMain(EventCardMain eventCardMain) {
//
//        if (eventCardMain != null) {
//
//            if (eventCardMain.getMessage() == ExtraValue.EVENTBUS_EVENT_TO_REFRESH_CARD_MAIN_LIST) {
//
//                LogUtils.d(ConstantSign.LOGCAT_NOMAL + "收到刷新主页历史记录列表的消息--EVENTBUS_EVENT_TO_REFRESH_CARD_MAIN_LIST");
//
//                //如果发起搜索，要重置 第1页
//                pagination_upLoad = Parameterkey.pageNum_default_first;
//
//                //清空历史数据
//                if (mDataResources != null && !mDataResources.isEmpty()) {
//                    mDataResources.clear();
//                }
//
//                if (cardSumHistoryAdapter != null) {
//                    cardSumHistoryAdapter.notifyDataSetChanged();
//                }
//
//                getServerDatas();
//
//            }
//
//        }
//
//    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

        if (cardSumHistoryAdapter != null) {
            cardSumHistoryAdapter.notifyDataSetChanged();
            cardSumHistoryAdapter = null;
        }

        CommUtils.checkMaterialDialog(materialDialogCustomView);

//        if (customAttachBg != null) {
//
//            if (customAttachBg.isShow()) {
//                customAttachBg.onDismiss();
//            }
//
//            customAttachBg.onDestroy();
//            customAttachBg = null;
//        }

//        EventBus.getDefault().unregister(this);

    }

    @Override
    protected void methodBack() {
        if (ActivityUtils.isActivityAlive(this)) {
            ActivityUtils.finishActivity(this);
        }
    }

    //2018年08月10日添加提取全选功能
    private void method_selectAll() {
        //默认是确定选中全选
        if (mDataResources != null && !mDataResources.isEmpty()) {

            //2018年08月09日去掉全选功能
            if (chooseListenerFunction != null) {
                chooseListenerFunction.chooseAllItem();
            }

        } else {
//            CommUtils.displayToastShort(PropertyPaymentActivity.this, "暂无数据");
            ToastUtils.showShort(getResources().getString(R.string.nulldatanow));
        }
    }

    //填充总价格内容
    private void method_total_size(final ArrayList<CouponCustomerVo> _dataResources) {

        //CommUtils.formatComma2BigDecimal(methodToatal(mDataResources)

        ArrayList<CouponCustomerVo> temps = new ArrayList<>();

        if (_dataResources != null && !_dataResources.isEmpty()) {

            for (int indexPosition = 0; indexPosition < _dataResources.size(); indexPosition++) {

                CouponCustomerVo item = _dataResources.get(indexPosition);
                int isChecked = item.getIsSelect();

                if (isChecked == 1) {

                    //被勾选的参与计算
                    temps.add(item);

                } else {
                    //未被选中，不参与结算。
                }
            }


        }

        if (textViewDataSize != null) {
            textViewDataSize.post(new Runnable() {
                @Override
                public void run() {

                    //CommUtils.setText(textViewAmount, mSession.getCurrencySymbol() + _totalPrice.toString());
                    if (temps != null && !temps.isEmpty()) {
                        textViewDataSize.setText(String.valueOf(temps.size()));
                    } else {
                        textViewDataSize.setText(ConstantSign.NUMBER_ZERO);
                    }

                }
            });
        }
    }

//    private BigDecimal methodToatal(ArrayList<PropertyPaymentBean> _datas) {
//
//        BigDecimal curPriceTotal = new BigDecimal(0);
//
//        if ((_datas != null) && (!_datas.isEmpty())) {
//
//            for (int index = 0; index < _datas.size(); index++) {
//
//                PropertyPaymentBean item = _datas.get(index);
//
//                int isChecked = item.getChecked();
//
//                if (isChecked == 1) {//被勾选的参与计算
//                    BigDecimal fee = item.getPayAmount();
//                    curPriceTotal = curPriceTotal.add(fee);
//                } else {
//                    //未被选中，不参与结算。
//                }
//
//            }
//
//        } else {
//            //不参与运算的
//            return curPriceTotal;
//        }
//
//        return curPriceTotal;
//
//    }

    @Override
    public void processExtraData() {

        //use the data received here
        Bundle bundle = this.getIntent().getExtras();

        if (bundle != null) {

            flag_jumpfrom_where = bundle.getInt(ExtraKey.EXTRA_JUMPFROM_WHERE);

            //是否是批量审核跳转携带值内容
//            extra_bundle.putBoolean(ExtraKey.EXTRA_ISCHECKED_MORE_ITEMS_FLAG, extra_ischecked_more_items_flag);
            extra_ischecked_more_items_flag = bundle.getBoolean(ExtraKey.EXTRA_ISCHECKED_MORE_ITEMS_FLAG);

            //携带这条优惠券数据本身，属于那一条优惠券大礼包下：
            couponPackId_upLoad = bundle.getString(ExtraKey.EXTRA_COUPONPACKID_UPLOAD);

            //LogUtils.d(ConstantSign.LOGCAT_NOMAL + extra_jumpfrom_where);

//            station_shopId_upLoad = bundle.getString(ExtraKey.EXTRA_ASSETINSIDEBEAN_SHOPID);

            //这个特殊，采用同一个对象；
            //服务站的顶部选择列表---这里取到的肯定是空值，因为上一个页面没有携带
//            extra_assetStationInfoListForAddAsset_loacalDB = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETSTATIONINFOLISTFORADDASSET);

            //资产的归属方 列表，
//            extra_assetUnderBusinessInfoListOutSide = bundle.getParcelableArrayList(ExtraKey.EXTRA_ASSETUNDERBUSINESSINFOLISTOUTSIDE);

        }

    }


}